class Label < ActiveRecord::Base
  #Relations
  belongs_to	:label
  belongs_to	:parent_label,
                :class_name => "Label",
                :foreign_key => "label_id"
  belongs_to	:forum
  belongs_to	:location
  
  has_many  :label_dates
  has_many	:images, :as => :photographable, :dependent => :destroy
  has_many	:reviews, :as => :reviewable, :dependent => :destroy
  has_many	:edits, :as => :editable, :order => "created_at DESC"
  has_many	:editions
  has_many	:label
  has_many	:child_label,
            :class_name => "Label",
            :foreign_key => "label_id"


  #Call backs
  after_update :create_edit
  after_create :new_entry_edit
  before_save  :add_forum

  #
  def to_s
    return name
  end

  #
  def to_param
    "#{id}-#{name.parameterize}"
  end

  def primary_image
    if images.empty?
      return nil
    else
      images.first.image
    end
  end


  private

  #
  #
  def add_forum
    if self.new_record?
      title = self.name + "'s Forum"
      forum = Forum.new(:title => title)
      forum.save!
      self.forum_id = forum.id
    end
  end

  #
  #
  def new_entry_edit
      entry = Hash.new
      entry.store("created", [self.name])
      Edit.create_edit(entry, self)
  end

  #
  #
  def create_edit
    if self.changed?
      Edit.create_edit(self.changes, self)
    end
  end

end
